package webcert.ch01.ex0103;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

public class RequestHeaders extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.write("<html><head></head><body>");

        Enumeration<String> headers = request.getHeaderNames();

        while (headers.hasMoreElements()) {
            String header = headers.nextElement();
            out.write("<h4>" + header + "</h4>");

            Enumeration<String> headerValues = request.getHeaders(header);
            while (headerValues.hasMoreElements()) {
                out.write(headerValues.nextElement());
            }
        }

        HttpSession session = request.getSession();

        out.write("<h3>Cookies:</h3>");
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie c : cookies) {
                out.write("<h4>Name</h4>: " + c.getName());
                out.write("<h4>Value</h4>: " + c.getValue());
                out.write("<h4>Domain</h4>: " + c.getDomain());
                out.write("<h4>Path</h4>: " + c.getPath());
                out.write("<h4>Comment</h4>: " + c.getComment());
                out.write("<h4>MaxAge</h4>: " + c.getMaxAge());
                out.write("<h4>Secure</h4>: " + c.getSecure());
                out.write("<h4>Version</h4>: " +c.getVersion());

            }
        }
        out.write("</body></html>");
        out.close();
    }
}
